package com.cookizz.waterfalldemo;

import java.util.ArrayList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap.Config;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;

public class MyAdapter extends BaseAdapter {

	private List<String> urls = new ArrayList<String>();
	private DisplayImageOptions options;
	private LayoutInflater mLayoutInflater;

	private class ViewHolder {
		public ImageView image;
	}

	public MyAdapter(Context context, List<String> data) {
		mLayoutInflater = LayoutInflater.from(context);
		urls = data;
		options = new DisplayImageOptions.Builder()
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Config.RGB_565)
				.build();
	}

	@Override
	public int getCount() {
		return urls.size();
	}

	@Override
	public Object getItem(int position) {
		return urls.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder vh;
		if (convertView == null) {
			convertView = mLayoutInflater.inflate(R.layout.waterfall_item,
					parent, false);
			vh = new ViewHolder();
			vh.image = (ImageView) convertView
					.findViewById(R.id.waterfall_image);
			convertView.setTag(vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		
		// set item margins
		android.widget.FrameLayout.LayoutParams params = (LayoutParams) vh.image.getLayoutParams();
		params.setMargins(5, 5, 5, 5);
		
		// load image
		String url = urls.get(position);
		ImageLoader.getInstance().displayImage(url, vh.image, options);

		return convertView;
	}

	public void loadNewPage() {
		List<String> page = ImagePageIterator.getNextPageList();
		urls.addAll(page);
		notifyDataSetChanged();
	}
}
